/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fifa.filter;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author CarlosAlberto
 */
public class SecurityFilter implements Filter {

    public static final String LOGGED_USER = "LOGGED_USER";
    public static final String IS_LOGGED_IN = "IS_LOGGED_IN";

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession session = request.getSession(false);

            boolean validUser = false;
            if (session != null) {
                Boolean isLoggedIn = (Boolean) session.getAttribute(IS_LOGGED_IN);
                
                if (Boolean.TRUE.equals(isLoggedIn)) {
                    validUser = true;
                }
            }
            if (validUser) {
                chain.doFilter(req, resp);
            } else {
                if(session!=null){
                    session.invalidate();
                }
                response.sendRedirect("/Informacion_MundialistaWeb/login.xhtml");
            }
        } catch (IOException | ServletException e) {
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE,
                    "Error en el filtro de seguridad", e);
        }
    }

    @Override
    public void destroy() {

    }

}
